package liuhe.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import liuhe.manager.CS2Manager;
import liuhe.manager.XJSManager;
import liuhe.tools.Common;

public class XJSHttp {
	CloseableHttpClient httpclient = null;
	RequestConfig requestConfig = null;
	HttpClientContext clientContext = null;
	
	 String ADDRESS = "";
	 String ACCOUNT = "";
	 String PWD = "";
	 
	 public long canLoginTime;
	 private int statusCode = -1;
	 private String token = "";
	 String strCookies = "";
	 
	 String currIssue = "";
	 String oldCurrIssue = "";
	 
	public int getStatusCode() {
	    return statusCode;
	}
	
	int defaultTimeout = 60*1000;
	
	 {
		 System.setProperty("https.protocols", "TLSv1.2");
		 System.setProperty("https.certificateVerification", "ignore");
		 HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
		 
		 
		 
	    requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
	   // requestConfig = RequestConfig.copy(requestConfig).setRedirectsEnabled(false).build();//��ֹ�ض��� �� �Ա��ȡcookieb18
	    
	   // requestConfig = RequestConfig.copy(requestConfig).setProxy(proxy).build();//ʹ�ô���
	    
	    requestConfig = RequestConfig.copy(requestConfig).setConnectTimeout(defaultTimeout).setConnectionRequestTimeout(defaultTimeout).setSocketTimeout(defaultTimeout).build();//���ó�ʱ
	        httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
	 }
	 
		public  void setLoginParams(String address, String account, String pwd){
			ADDRESS = address;
			ACCOUNT = account;
			PWD = pwd;
		}
		
		public long getCanLoginTime() {
	      	return canLoginTime;
	    }
		
	    // 1�ɹ�	 -1��¼ʧ��, -2ά�� , -3�˺��쳣 , -4���벻��ȷ , 2ץȡ�ɹ�, 3ץȡʧ��
	    public void updateStatusCode(int i) {

	    	if(i == -2) {
	    		canLoginTime = System.currentTimeMillis() + 5*60*1000;
	    	}
	    	

	    	//Common.logOut(ACCOUNT + "  update hg_statusCode from " +   Integer.toString(statusCode) + " to " + Integer.toString(i));
	    	
	   	 statusCode = i;
	    
	    }
		
	    public  CloseableHttpResponse  execute(HttpUriRequest request) throws Exception{
	    	
	    	long time1 = System.currentTimeMillis();
	    	long time2 = System.currentTimeMillis();
	    	
	    	CloseableHttpResponse response;
	    	
	    	
	    	SimpleDateFormat dfsec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	
	    	
	    	try{
	    		Thread.sleep(100);
	    		//Thread.sleep(1200);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    	
	    	
	    	
	    	
	    	//Common.logOut("excecute time:" + dfsec.format(time1));
	    	
	    	
	    	try{
	    		response = httpclient.execute(request);    		
	    		time2 = System.currentTimeMillis();    		
	    		
	    	}catch(Exception e){
	    		
	    		time2 = System.currentTimeMillis();
	    		
	    		throw e;
	    	}
	    	

	    	
	    	return response;
	    	
	    }
	    
		public String setCookie(CloseableHttpResponse httpResponse)
		{
			//strCookies = "";
			//Common.logOut("----setCookieStore");
			Header headers[] = httpResponse.getHeaders("Set-Cookie");
			if (headers == null || headers.length==0)
			{
				//Common.logOut("----there are no cookies");
				return null;
			}

			String cookie = "";
			for (int i = 0; i < headers.length; i++) {
				cookie += headers[i].getValue();
				if(i != headers.length-1)
				{
					cookie += ";";
				}
			}
			String cookies[] = cookie.split(";");
			
			for (String c : cookies)
			{
				if(c.indexOf("path=") != -1 || c.indexOf("expires=") != -1 || c.indexOf("domain=") != -1 || c.indexOf("HttpOnly") != -1)
					continue;
				strCookies += c;
				strCookies += ";";
			}
			//Common.logOut("----setCookieStore success");

			return strCookies;
		}
	    
	    
	    public String doGet(String url, String cookies, String referUrl) {
	    	
	        try {  
	            // ����httpget.    
	            HttpGet httpget = new HttpGet(url);
	            
	            if(cookies != "") {
	            	httpget.addHeader("Cookie",cookies);
	            }
	            httpget.addHeader("Accept-Encoding","gzip, deflate, br, zstd");
	            httpget.addHeader("Accept-Language","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
	            httpget.addHeader("Connection","keep-alive");	            
	            httpget.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
	            
	            httpget.addHeader("X-Requested-With","XMLHttpRequest");
	            

	            
	            httpget.addHeader("Upgrade-Insecure-Requests","1");
	            
	            httpget.addHeader("Priority","u=0, i");
	            
	            //
	            
	            if(referUrl != "")
	            {
	            	httpget.addHeader("Referer",referUrl);
	            	
	            }
	            
	            httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");           
	           // Common.logOut("executing request " + httpget.getURI()); 
	           
	            //���ó�ʱ
	            
//	            HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
//	            
//	            RequestConfig requestConfigtmp = RequestConfig.custom().setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
//	            requestConfigtmp= RequestConfig.copy(requestConfigtmp).setProxy(proxy).build();
//	            httpget.setConfig(requestConfigtmp);
	            
	            // ִ��get����.    
	            CloseableHttpResponse response = execute(httpget); 
	            
	            String statusLine = response.getStatusLine().toString();   
	            if(statusLine.indexOf("200 OK") == -1) {
	         	  // Common.logOut(statusLine); 
	            }
	            
	            try{
	            	setCookie(response);  	
	            	//Common.logOut("����cookie:" + strCookies);
	            	
	            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
	             	   return response.getFirstHeader("Location").getValue();
	                }
	                HttpEntity entity = response.getEntity(); 
	                
	                String res = EntityUtils.toString(entity);
	                
	                if(res != null && res.length() > 0 ){     
	                	//Common.logOut(res);
	                	
//	                	if(res.contains("logout_warn")) {
//	                		updateStatusCode(-1);
//	                	}
	                	
	                    return res;
	                }
	            }finally{
	                httpget.releaseConnection();
	                response.close();
	            }
	            

	            

	        } catch (ClientProtocolException e) {  
	            e.printStackTrace(); 
	        } catch (ParseException e) {  
	            e.printStackTrace(); 
	        } catch (IOException e) {  
	            e.printStackTrace(); 
	        } catch (Exception e){
	        	e.printStackTrace();
	        }
	        
	        return null;
	    }
	    
	    public String doPost(String url,List<NameValuePair> formparams, String cookies, HttpPost httppost) {
	        return doPost(url, formparams,"UTF-8", cookies, httppost);
	    }

	    public String doPost(String url,List<NameValuePair> formparams,String charset, String cookies, HttpPost httppost) {


	     // ����httppost   
	    	
	    	try {
	    	


	        //httppost.addHeader("Referer",ADDRESS+"/html/login/2022/");

	        if(formparams!=null) {
		        UrlEncodedFormEntity uefEntity;
		        
	            uefEntity = new UrlEncodedFormEntity(formparams, charset);
	            httppost.setEntity(uefEntity);
	        }

	            
	            
	            
	            
//	            HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
//	            
	//
//	            
//	            
//	            
//	            RequestConfig requestConfigtmp = RequestConfig.custom().setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
//	            requestConfigtmp= RequestConfig.copy(requestConfigtmp).setProxy(proxy).build();
//	            httppost.setConfig(requestConfigtmp);
	            
	            CloseableHttpResponse response = execute(httppost);
	            try {
	                // ��ӡ��Ӧ״̬    
	            	//setCookie(response);
	            	//Common.logOut("����cookie:" + strCookies);
	            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
	            		String location = response.getFirstHeader("Location").getValue();
	            		//Common.logOut(response.getStatusLine());
	            		
	            		
	            		
	            		if(location != null) {
	            			return location;
	            		}
	            	}
	            	
	            	
	            	
	            	//Header headers[] = response.getHeaders("Content-Type");
	            	
	            	
	                HttpEntity entity = response.getEntity(); 
	                
	                String res = "";
	                
	                if(url.contains("get_today_ft_league_wager.php") || url.contains("app/ft/get_today_ft_allbets_wager.php")){            		
	                	res = new  String(EntityUtils.toString(entity).getBytes("ISO-8859-1"), "UTF-8");
	                }else{
	                	res = EntityUtils.toString(entity);
	                }
	                
	                
	                if(res != null && res.length() > 0 ){   

//	                	if(res.contains("logout_warn")) {
//	                		updateStatusCode(-1);
//	                	}
	                	
	                	//Common.logOut(res);
	                    return res;
	                }
	            	
	            	

	            } finally {  
	            	httppost.releaseConnection();
	                response.close(); 
	            }  
	        } catch (ClientProtocolException e) {  
	            e.printStackTrace(); 
	        } catch (UnsupportedEncodingException e1) {  
	            e1.printStackTrace(); 
	        } catch (IOException e) {  
	            e.printStackTrace(); 
	     
	        } catch(Exception e){
	     	   e.printStackTrace();
	        } 
	        return null;
	    }
	    
	    
	    public String getPicNum(String picUri) {
	    	try {
		   	    HttpGet httpget = new HttpGet(picUri);
		        httpget.addHeader("Connection","keep-alive");
		
		        httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36");
		        httpget.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
		        httpget.addHeader("Accept-Encoding","gzip, deflate, br, zstd");
		        httpget.addHeader("Accept-Language","zh-CN,zh;q=0.9");
		        httpget.addHeader("Host",ADDRESS.replace("https://", ""));

	            
		        CloseableHttpResponse response = execute(httpget); 
	       	 try {

	                // ��ӡ��Ӧ״̬    
	               // Common.logOut(response.getStatusLine()); 

	                File storeFile = new File(ACCOUNT+"XJS.png");   //ͼƬ���浽��ǰλ��
	                FileOutputStream output = new FileOutputStream(storeFile);  
	                //�õ�������Դ���ֽ�����,��д���ļ�  

	                
	                byte [] a = EntityUtils.toByteArray(response.getEntity());
	               // Common.logOut(bytesToHex(a));
	                output.write(a);  
	                output.close();  
	                
	                
	                
	                String url = "http://103.234.98.153:8089/api/tr-run/";
	                File file = new File(ACCOUNT+"XJS.png");

                    HttpPost httpPost = new HttpPost(url);

                    // ����MultipartEntityBuilder�������ಿ�ֱ�����
                    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    builder.addPart("file", new FileBody(file));  // �ϴ��ļ�
                    builder.addPart("compress", new StringBody("0"));  // ����������

                    // ����������
                    HttpEntity entity = builder.build();
                    httpPost.setEntity(entity);

                    // ִ�����󲢻�ȡ��Ӧ

                	response = httpclient.execute(httpPost);
                    // ��ȡ��Ӧ�岢ת��Ϊ�ַ���
                    String responseString = EntityUtils.toString(response.getEntity());

                    // �����Ӧ����
                    
                    
                    if(responseString.contains("raw_out")) {
                        ObjectMapper objectMapper = new ObjectMapper();

                        // �� JSON �ַ�������Ϊ JsonNode
                        JsonNode rootNode = objectMapper.readTree(responseString);

                        // ��ȡ "data" �ڵ�
                        JsonNode dataNode = rootNode.path("data");

                        // ��ȡ "raw_out" ����
                        JsonNode rawOutNode = dataNode.path("raw_out");

                        // ��ȡ "raw_out" �����еĵ�һ��Ԫ��
                        JsonNode firstRawOutNode = rawOutNode.get(0);

                        // ��ȡ�ڶ���Ԫ�أ��� "1240"��
                        String extractedValue = firstRawOutNode.get(1).asText();

                        extractedValue = extractedValue.replace("^", "4");
                        extractedValue = extractedValue.replace("g", "8");
                        extractedValue = extractedValue.replace(">", "7");
                        extractedValue = extractedValue.replace(",", "8");
                        extractedValue = extractedValue.replace("o", "0");
                        extractedValue = extractedValue.replace("Z", "2");
                        
                        
                        if (extractedValue.matches("^\\d{4}$")) {
                            
                            return extractedValue;
                        } 
                    }

//	        		File file = new File(ACCOUNT+"fuan.jpg");
//	        		ITesseract tesseract = new Tesseract();
//	        		tesseract.setDatapath("tessdata");
//	        		String result = "";
//	       			result = tesseract.doOCR(file);
//	       			result = result.replaceAll("\\s*|\r|\n|\t", "");
//	        		//Common.logOut(result);
//	       			
//	       			Header[] headers = response.getHeaders("Set-Cookie");
//	       			for (Header header : headers) {
//	       			    BasicClientCookie cookie = new BasicClientCookie(header.getName(), header.getValue());
//	       			    cookie.setDomain(httpget.getURI().getHost());
//	       			    cookie.setPath("/");
//	       			    cookieStore.addCookie(cookie);
//	       			}
	       			
	       			//cookieStore.addCookie((org.apache.http.cookie.Cookie) response.getFirstHeader("Set-Cookie"));
	       			
	                return "";
	       	 }catch(Exception e) {
	       		 e.printStackTrace();
	       	 }
	       	 finally{
	       		httpget.releaseConnection();
	       		 response.close(); 
	       	 }
	        } catch (ClientProtocolException e) {  
	            e.printStackTrace(); 
	        } catch (UnsupportedEncodingException e1) {  
	            e1.printStackTrace(); 
	        } catch (IOException e) {  
	            e.printStackTrace(); 
	        } catch (Exception e) {
					e.printStackTrace();
			 }
	        
	   	return null;
	   }
	    
	    
//	    public String doPost(String url,String formparams, String cookies, HttpPost httppost) {
//	        return doPost(url, formparams,"UTF-8", cookies, httppost);
//	    }
//
//	    public String doPost(String url,String formparams,String charset, String cookies, HttpPost httppost) {
//
//
//	     // ����httppost   
//	    	
//	    	try {
//	    	
//
//
//	        StringEntity requestEntity = new StringEntity(formparams,"utf-8");
//
//	           requestEntity.setContentEncoding("UTF-8");
//	           httppost.setEntity(requestEntity);
//
//
//	            
//	            
//	            
////	            HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
////	            
//	//
////	            
////	            
////	            
////	            RequestConfig requestConfigtmp = RequestConfig.custom().setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
////	            requestConfigtmp= RequestConfig.copy(requestConfigtmp).setProxy(proxy).build();
////	            httppost.setConfig(requestConfigtmp);
//	            
//	            CloseableHttpResponse response = execute(httppost);
//	            try {
//	                // ��ӡ��Ӧ״̬    
//	            	//setCookie(response);
//	            	//Common.logOut("����cookie:" + strCookies);
//	            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
//	            		String location = response.getFirstHeader("Location").getValue();
//	            		//Common.logOut(response.getStatusLine());
//	            		
//	            		
//	            		
//	            		if(location != null) {
//	            			return location;
//	            		}
//	            	}
//	            	
//	            	
//	            	
//	            	//Header headers[] = response.getHeaders("Content-Type");
//	            	
//	            	
//	                HttpEntity entity = response.getEntity(); 
//	                
//	                String res = "";
//	                
//	                if(url.contains("get_today_ft_league_wager.php") || url.contains("app/ft/get_today_ft_allbets_wager.php")){            		
//	                	res = new  String(EntityUtils.toString(entity).getBytes("ISO-8859-1"), "UTF-8");
//	                }else{
//	                	res = EntityUtils.toString(entity);
//	                }
//	                
//	                
//	                if(res != null && res.length() > 0 ){   
//
////	                	if(res.contains("logout_warn")) {
////	                		updateStatusCode(-1);
////	                	}
//	                	
//	                	//Common.logOut(res);
//	                    return res;
//	                }
//	            	
//	            	
//
//	            } finally {  
//	            	httppost.releaseConnection();
//	                response.close(); 
//	            }  
//	        } catch (ClientProtocolException e) {  
//	            e.printStackTrace(); 
//	        } catch (UnsupportedEncodingException e1) {  
//	            e1.printStackTrace(); 
//	        } catch (IOException e) {  
//	            e.printStackTrace(); 
//	     
//	        } catch(Exception e){
//	     	   e.printStackTrace();
//	        } 
//	        return null;
//	    }
	    
	    public int login(){// 1�ɹ�	 -1��¼ʧ��, -2ά�� , -3�˺��쳣, -4���벻��ȷ	    	
	    	try{		  
	    		
	    		String loginPage = doGet(ADDRESS+"/", "", "");

	        	String code = getPicNum(ADDRESS+"/index.php?controller=privilege&action=ImgCode&0.2958618897824863");
	        	
	        	if (code.matches("^\\d{4}$")) {
	        		
	        		List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
		        	loginParams.add(new BasicNameValuePair("username", ACCOUNT));
		        	loginParams.add(new BasicNameValuePair("password", PWD));
		        	loginParams.add(new BasicNameValuePair("imgcode", code));
		        	loginParams.add(new BasicNameValuePair("glcode", ""));

			        HttpPost httppost = new HttpPost(ADDRESS+"/index.php?controller=privilege&action=login"); 

	    	        httppost.addHeader("Accept-Language","Accept-Language: zh-CN");
	    	        httppost.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
	    	        httppost.addHeader("Accept-Encoding","gzip, deflate");
	    	        httppost.addHeader("Connection","keep-alive");
	    	        httppost.addHeader("Cache-Control","max-age=0");
	    	        httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");    
		        	
		        	String res = doPost("", loginParams, "",httppost);		        	
		        	
		        	if(res.contains("index.php")) {
		        		String res1 = doGet(ADDRESS+res,"",ADDRESS+"/html/login/2022/");
		        		if(res1.contains("admin_index")) {
		        			Common.logOut(ACCOUNT+ " XJS login success ");
			        		updateStatusCode(1);
			        		return 1;
		        		}

		        	}
		        	
		        	Common.logOut(ACCOUNT+ " XJS login failed " + res);
	        	}

	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    	updateStatusCode(-1);    	
	    	return -1;
	    }
	    
	    public boolean getLotteryIssueInfo() {
	    	try {
		    	try {

		    		String res = doGet(ADDRESS+"/index.php?Y29udHJvbGxlcj1nYW1yYXRlJmFjdGlvbj1zaG93cmF0ZSZwaWQ9MzUmdG9wY29kZT14YW1saA==/", "", "");
	    	        if(res.contains("g_cycleid")) {
	    	        	Pattern pattern = Pattern.compile("var g_cycleid='([^']+)';");
	    	            Matcher matcher = pattern.matcher(res);

	    	            // ����ƥ��Ĳ���
	    	            if (matcher.find()) {
	    	                // ��ȡ����ӡ g_cycleid ������ַ���
	    	                String gCycleId = matcher.group(1);
	    	                currIssue = gCycleId.replace("-", "");               
	    	                return true;
	    	            } 
	    	        }else {
	    	        	updateStatusCode(-1); 
	    	        }
		    	}catch(Exception e) {
		    		e.printStackTrace();
		    	}
	    	}catch(Exception e) {
	    		e.printStackTrace();
	    	}
	    	return false;
	    }
	    

	    
	    
	    
	    public void getActualData() {
	    	try {
	    		
	    		JSONObject currentData = new JSONObject();
	    		currentData.put("msg", "FAILED");
	    		currentData.put("account", ACCOUNT);
	    		boolean success = getLotteryIssueInfo();
	    		if(success==false) {
	    			return;
	    		}
    			String res = doGet(ADDRESS+"/index.php?controller=admin_index&action=OpenInfobylot&code=xamlh", "", "");

		        HttpPost httppost = new HttpPost(ADDRESS+"/index.php?Y29udHJvbGxlcj1nYW1yYXRlJmFjdGlvbj1zaG93cmF0ZQ==/&lid=1974&code=xamlh_tm2&&1=1&stypes=&selectsid=&is_stock=0&region=all&orderby=result&is_ajax=1"); 
    	        httppost.addHeader("Accept-Language","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
    	        httppost.addHeader("Accept-Encoding","gzip, deflate, br, zstd");
    	        httppost.addHeader("Connection","keep-alive");
    	        httppost.addHeader("Cache-Control","max-age=0");
    	        httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");    
 
	    		res = doPost("", null,"",httppost);
	    		JSONArray ja1 = new JSONArray();
	    		if(res.contains("金额")) {//̓ע
	    	        // ����HTML
	    	        Document document = Jsoup.parse(res);
	    	        
	    	        // �ҵ����
	    	        Elements rows = document.select("table.mydata tr");
	    	        
	    	        // ����ÿһ�У���ȡ���롢���ͷ���
	    	        for (Element row : rows) {
	    	            // ��ȡÿһ���е�������
	    	            Elements cols = row.select("td");

	    	            // �������������
	    	            if (cols.size() > 3) {
	    	                // ��ȡ���룬���ͷ���

	    	                String number = cols.get(0).text(); // ��ȡ����
	    	                if(!number.matches("^\\d{2}$")) {
	    	                	continue;
	    	                }
	    	                String amount = cols.get(2).text(); // ��ȡ���
	    	                String risk = cols.get(3).text(); // ��ȡ����
	    	                JSONObject newItem = new JSONObject();
	  	        			 newItem.put("amount", amount);
	  	        			 newItem.put("contents", number);
	  	        			 newItem.put("earnings", risk);  
	  	        			 ja1.put(newItem);

	    	            }
	    	        }
	    	        
	    	        currentData.put("data", ja1);
	    	        

	    	        
	    		}else {
	    			Common.logOut(ACCOUNT + "XJS getActualData failed " + res);
	    			updateStatusCode(-1); 
	    			return;
	    		}	
	    		
	    		
	    		
	    		
	    		//yxdata
	    		JSONArray ja2 = new JSONArray();
	    		res = doGet(ADDRESS+"/index.php?Y29udHJvbGxlcj1nYW1yYXRlJmFjdGlvbj1zaG93cmF0ZQ==/&code=xamlh_sxy&topcode=xamlh&rusername=","","");
	    		
	    		
	    		if(res.contains("金额")) {
	    			 // 使用Jsoup解析HTML
	    	        Document doc = Jsoup.parse(res);
	    	        Map<String, String> categoryAmountMap = new LinkedHashMap<>();
	    	        // 遍历所有<tr>标签
	    	        Elements rows = doc.select("tr:has(td.td_name)");
	    	        for (Element row : rows) {
	    	            // 提取“种类”（<td class='td_name'>）
	    	            Element categoryElement = row.select("td.td_name").first();
	    	            if (categoryElement == null) continue;
	    	            String category = categoryElement.text();
	    	            
	    	            boolean isNumeric = category.matches(".*\\d.*");
	    				if(isNumeric) {
	    					continue;
	    				}
	    	            
	    	            // 提取“金额”（<a id^='cash_'>）
	    	            Element amountElement = row.select("a[id^=cash_]").first();
	    	            if (amountElement == null) continue;
	    	            String amount = amountElement.text();
	    	            // 存入Map
	    	            
	    	         // 避免重复：检查是否已存在该种类
	    	            if (!categoryAmountMap.containsKey(category)) {
	    	                categoryAmountMap.put(category, amount);
		    	            JSONObject newItem = new JSONObject();
	  	        			newItem.put("amount", amount);	 
	   	        			newItem.put("contents", category);
		    	            ja2.put(newItem);
	    	            } else {
	    	                System.err.println("发现重复种类: " + category);
	    	            }
	    	            

	    	        }

	    	        
	    	         currentData.put("msg", "SUCCESS");
 	    	         
	    	         currentData.put("yxdata", ja2);
	    	         currentData.put("grabtime", System.currentTimeMillis());
	    	         currentData.put("currIssue", currIssue);
	    	         currentData.put("currOpenTime", 0);
	    	         currentData.put("sellTime", 0);
	    	         XJSManager.dataJArray.put(currentData);
	    	        Common.logOut((ACCOUNT+ " XJS ActualData success " ) + currentData.toString());
	    	        
	    		}else {
	    			Common.logOut(ACCOUNT + "CS2 getActualData failed " + res);
	    			updateStatusCode(-1); 
	    			return;
	    		}
	    		
	    		
	    		
	    		
       
	    	}catch(Exception e) {
	    		e.printStackTrace();
	    	}
	    }
	    
	    
	    public boolean getOldLotteryIssueInfo() {
	    	try {
		    	try {

		    		String res = doGet(ADDRESS+"/index.php?Y29udHJvbGxlcj1nYW1yYXRlJmFjdGlvbj1zaG93cmF0ZSZwaWQ9MjMmdG9wY29kZT1iamFtbGg=/", "", "");
	    	        if(res.contains("g_cycleid")) {
	    	        	Pattern pattern = Pattern.compile("var g_cycleid='([^']+)';");
	    	            Matcher matcher = pattern.matcher(res);

	    	            // ����ƥ��Ĳ���
	    	            if (matcher.find()) {
	    	                // ��ȡ����ӡ g_cycleid ������ַ���
	    	                String gCycleId = matcher.group(1);
	    	                oldCurrIssue = gCycleId.replace("-", "");               
	    	                return true;
	    	            } 
	    	        }else {
	    	        	updateStatusCode(-1); 
	    	        }
		    	}catch(Exception e) {
		    		e.printStackTrace();
		    	}
	    	}catch(Exception e) {
	    		e.printStackTrace();
	    	}
	    	return false;
	    }
	    
	    public void getOldActualData() {
	    	try {
	    		
	    		JSONObject currentData = new JSONObject();
	    		currentData.put("msg", "FAILED");
	    		currentData.put("account", ACCOUNT);
	    		boolean success = getOldLotteryIssueInfo();
	    		if(success==false) {
	    			return;
	    		}
    			String res = doGet(ADDRESS+"/index.php?controller=admin_index&action=OpenInfobylot&code=bjamlh", "", "");

		        HttpPost httppost = new HttpPost(ADDRESS+"/index.php?Y29udHJvbGxlcj1nYW1yYXRlJmFjdGlvbj1zaG93cmF0ZQ==/&lid=1974&code=bjamlh_tm2&&1=1&stypes=&selectsid=&is_stock=0&region=all&orderby=result&is_ajax=1"); 
    	        httppost.addHeader("Accept-Language","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
    	        httppost.addHeader("Accept-Encoding","gzip, deflate, br, zstd");
    	        httppost.addHeader("Connection","keep-alive");
    	        httppost.addHeader("Cache-Control","max-age=0");
    	        httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");    
 
	    		res = doPost("", null,"",httppost);
	    		JSONArray ja1 = new JSONArray();
	    		if(res.contains("金额")) {//̓ע
	    	        // ����HTML
	    	        Document document = Jsoup.parse(res);
	    	        
	    	        // �ҵ����
	    	        Elements rows = document.select("table.mydata tr");
	    	        
	    	        // ����ÿһ�У���ȡ���롢���ͷ���
	    	        for (Element row : rows) {
	    	            // ��ȡÿһ���е�������
	    	            Elements cols = row.select("td");

	    	            // �������������
	    	            if (cols.size() > 3) {
	    	                // ��ȡ���룬���ͷ���

	    	                String number = cols.get(0).text(); // ��ȡ����
	    	                if(!number.matches("^\\d{2}$")) {
	    	                	continue;
	    	                }
	    	                String amount = cols.get(2).text(); // ��ȡ���
	    	                String risk = cols.get(3).text(); // ��ȡ����
	    	                JSONObject newItem = new JSONObject();
	  	        			 newItem.put("amount", amount);
	  	        			 newItem.put("contents", number);
	  	        			 newItem.put("earnings", risk);  
	  	        			 ja1.put(newItem);

	    	            }
	    	        }
	    	        
 	    	         currentData.put("msg", "SUCCESS");
 	    	         currentData.put("data", ja1);
 	    	         //currentData.put("sharedata", ja2);
 	    	         currentData.put("grabtime", System.currentTimeMillis());
 	    	         currentData.put("currIssue", oldCurrIssue);
 	    	         currentData.put("currOpenTime", 0);
 	    	         currentData.put("sellTime", 0);
 	    	         XJSManager.oldDataJArray.put(currentData);
	    	        Common.logOut((ACCOUNT+ " XJS old ActualData success" ));
	    	        
	    		}else {
	    			Common.logOut(ACCOUNT + "XJS old getActualData failed " + res);
	    			updateStatusCode(-1); 
	    			return;
	    		}	    		
       
	    	}catch(Exception e) {
	    		e.printStackTrace();
	    	}
	    }
	    
}
